package com.example.routelink.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import com.example.routelink.gateway.entity.ResultEnum;
import com.example.routelink.gateway.utils.IpUtils;
import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.util.SubnetUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class WhiteListFilterGatewayFilterFactory extends BaseFilter<WhiteListFilterGatewayFilterFactory.Config> implements Ordered {
    public WhiteListFilterGatewayFilterFactory() {
        super(WhiteListFilterGatewayFilterFactory.Config.class);
    }

    private static List<String> ipList;

    private static List<String> subnetMaskList;

    private final String filterName = "白名单";

    @PostConstruct
    private void init() {
        ipList = FileUtil.readUtf8Lines(System.getProperty("user.dir") + "\\config\\whiteList.txt");
        subnetMaskList = FileUtil.readUtf8Lines(System.getProperty("user.dir") + "\\config\\whiteSubnetMaskList.txt");
    }

    @Override
    public GatewayFilter apply(WhiteListFilterGatewayFilterFactory.Config config) {
        return (exchange, chain) -> {
            long startTime = System.currentTimeMillis();
            String ip = IpUtils.getRealIpAddress(exchange.getRequest());
            if (!Validator.isIpv4(ip)) {
                writeLog(filterName, startTime, "校验失败,非 ipv4地址，用户IP是 {} ", ip);
                return response(exchange, ResultEnum.ErrWhiteList);
            }
            if (CollUtil.isNotEmpty(ipList) && CollUtil.contains(ipList, ip)) {
                writeLog(filterName, startTime, "校验通过,用户IP是 {} ", ip);
                return chain.filter(exchange);
            }
            if (CollUtil.isNotEmpty(subnetMaskList)) {
                for (String subnetMask : subnetMaskList) {
                    SubnetUtils utils = new SubnetUtils(subnetMask);
                    SubnetUtils.SubnetInfo info = utils.getInfo();
                    if (info.isInRange(ip)) {
                        writeLog(filterName, startTime, "校验通过,用户IP是 {} ,匹配到白名单网段 {} ", ip, subnetMask);
                        return chain.filter(exchange);
                    }
                }
            }
            writeLog("白名单", startTime, "校验失败,用户IP是 {} 不在白名单内 ", ip);
            return response(exchange, ResultEnum.ErrWhiteList);
        };
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Data
    public static class Config {

    }
}
